package com.zhq.blog.manage.domain.controller.support;


import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class PageNumberUpdateAspector {

	@Around("execution(org.springframework.data.domain.Page com.zhq.blog.core.domain.admin..*.*Repository.findAll(..))")
	public Object processTx(ProceedingJoinPoint joinPoint)
			throws java.lang.Throwable {

		Object result = joinPoint.proceed(joinPoint.getArgs());

		if (((Page<?>) result).getContent().size() == 0) {
			Object[] params = joinPoint.getArgs();
			for (int i = 0; i < params.length; i++) {
				if (params[i] instanceof Pageable) {
					Pageable pageable = (Pageable) params[i];
					if((pageable.getPageNumber()+1)>((Page<?>) result).getTotalPages() && ((Page<?>) result).getTotalPages() >0){
						params[i]=new PageRequest(((Page<?>) result).getTotalPages()-1,pageable.getPageSize(),pageable.getSort());
						result = joinPoint.proceed(params);
						break;
					}else if(pageable.getPageNumber()<0){
						params[i]=new PageRequest(0,pageable.getPageSize(),pageable.getSort());
						result = joinPoint.proceed(params);
						break;
					}else{
						if (((Pageable) params[i]).hasPrevious()) {
							params[i] = ((Pageable) params[i]).previousOrFirst();
							result = joinPoint.proceed(params);
							break;
						}
					}
				}
			}
		}

		return result;
	}

}
